import os
import cv2
import time
import threading
import numpy as np
from PIL import ImageGrab
from datetime import datetime
from ui_untitled import Ui_MainWindow  # 从ui_xxx.py导入ui界面类
from PyQt5.QtWidgets import QMainWindow, QFileDialog, QApplication, QStyle, QSystemTrayIcon, QMenu
import sys
import warnings
from PyQt5.QtCore import Qt, QPoint, QTimer
from PyQt5.QtGui import QIcon
import reprint

warnings.filterwarnings("ignore", category=DeprecationWarning)


class myUI(QMainWindow):
    def __init__(self):
        super().__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.setting_path = os.path.dirname(os.path.abspath(__file__)) + '/setting.ini'  # 配置文件路径
        # 确保配置文件存在
        if not os.path.exists(self.setting_path):
            with open(self.setting_path, 'w') as f:
                f.write('')
        with open(self.setting_path, 'r') as f:
            self.folder_path = f.readline().strip()
            if self.folder_path == '':
                self.folder_path = os.path.dirname(os.path.abspath(__file__))  # 默认文件路径
            print("当前输出路径为：" + self.folder_path)
        self.initUIconnect()
        self.original_qss = self.styleSheet()
        self.setWindowFlags(Qt.WindowStaysOnTopHint | Qt.WindowCloseButtonHint)  # 置顶+只显示关闭按钮
        self.trayicon = QSystemTrayIcon(self)
        self.init_tray()
        self.record_end_flag = True
        reprint.reprint2log_start()
        self.old_pos = QPoint()

    def run(self):
        self.record_end_flag = False
        th = threading.Thread(target=self.video_record)
        th.start()
        self.ui.record_btn.clicked.disconnect()
        self.ui.record_btn.clicked.connect(self.stop)
        self.ui.record_btn.setIcon(self.style().standardIcon(QStyle.SP_MediaStop))
        if self.isVisible():
            self.display_hide()
        # 如果托盘菜单存在，也同步文本
        if hasattr(self, 'tray_record_action'):
            self.tray_record_action.setText('停止录制')

    def stop(self):
        self.record_end_flag = True
        from PyQt5.QtCore import QTimer
        QTimer.singleShot(1000, self.display_info)  # 延迟恢复界面
        self.video_info()
        self.ui.record_btn.clicked.disconnect()
        self.ui.record_btn.clicked.connect(self.run)
        self.ui.record_btn.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay))
        # 如果托盘菜单存在，也同步文本
        if hasattr(self, 'tray_record_action'):
            self.tray_record_action.setText('开始录制')

    def select_folder(self):
        # 弹出文件夹选择窗口
        self.folder_path = QFileDialog.getExistingDirectory(self, "Select Folder")
        if self.folder_path:
            with open('setting.ini', 'w') as f:
                f.write(self.folder_path)
                print("当前输出路径为：" + self.folder_path)
            self.ui.label.setText(self.folder_path)

    def video_record(self):
        self.name = datetime.now().strftime('%Y-%m-%d %H-%M-%S')  # 文件名
        screen = ImageGrab.grab()
        width, height = screen.size
        # 直接保存为 mp4
        fourcc = cv2.VideoWriter_fourcc(*'mp4v')
        video = cv2.VideoWriter(f'{self.folder_path}/{self.name}.mp4', fourcc, 20, (width, height))
        print('开始录制!')
        self.start_time = time.time()
        while True:
            if self.record_end_flag:
                print("录制结束！")
                self.final_time = time.time()
                video.release()
                break
            im = ImageGrab.grab()
            imm = cv2.cvtColor(np.array(im), cv2.COLOR_RGB2BGR)
            video.write(imm)

    def video_info(self):
        video = cv2.VideoCapture(f'{self.folder_path}/{self.name}.mp4')
        fps = video.get(cv2.CAP_PROP_FPS)
        count = video.get(cv2.CAP_PROP_FRAME_COUNT)
        size = (int(video.get(cv2.CAP_PROP_FRAME_WIDTH)), int(video.get(cv2.CAP_PROP_FRAME_HEIGHT)))
        text = '视频信息：\n'
        text += '帧率=%.1f\n' % fps
        text += '帧数=%.1f\n' % count
        text += '分辨率=%dx%d\n' % size
        text += '视频时间=%.3f秒\n' % (count / fps)
        text += '录制时间=%.3f秒\n' % (self.final_time - self.start_time)
        text += '推荐帧率=%.2f\n' % (fps * ((count / fps) / (self.final_time - self.start_time)))
        self.ui.msg_lable.setText(text)

    def initUIconnect(self):
        self.ui.record_btn.clicked.connect(self.run)
        self.ui.change_filepath_btn.clicked.connect(self.select_folder)
        self.ui.label.setWordWrap(True)
        self.ui.label.setText(self.folder_path)
        self.ui.record_btn.setText("")
        self.ui.record_btn.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay))

    def display_hide(self):
        # 隐藏窗口再改标志，避免刷新不生效
        self.hide()
        self.setWindowFlags(Qt.WindowStaysOnTopHint | Qt.FramelessWindowHint)
        self.setAttribute(Qt.WA_TranslucentBackground, True)  # 设置窗口透明

        # 隐藏多余控件，只保留录制按钮
        self.ui.label.hide()
        self.ui.msg_lable.hide()
        self.ui.change_filepath_btn.hide()
        self.ui.comboBox.hide()

        # 调整窗口大小和按钮位置
        self.ui.record_btn.move(1, 1)
        self.resize(self.ui.record_btn.width() + 2, self.ui.record_btn.height() + 2)
        self.ui.record_btn.setIcon(self.style().standardIcon(QStyle.SP_MediaStop))

        # 重新显示窗口
        self.show()

    def display_info(self):
        # 隐藏窗口再改标志，避免刷新不生效
        self.hide()
        self.setWindowFlags(Qt.WindowStaysOnTopHint | Qt.WindowCloseButtonHint)
        self.setAttribute(Qt.WA_TranslucentBackground, False)  # 取消透明

        # 恢复 QSS（保存在 __init__ 里的原始样式）
        self.setStyleSheet(self.original_qss)

        # 调整窗口大小和控件
        self.resize(300, 200)  # 你可以改成合适的大小
        self.ui.record_btn.move(90, 13)

        # 显示所有控件
        self.ui.label.show()
        self.ui.msg_lable.show()
        self.ui.change_filepath_btn.show()
        self.ui.comboBox.show()
        self.ui.record_btn.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay))

        # 重新显示窗口
        self.show()

    def mousePressEvent(self, event):
        if event.button() == Qt.LeftButton:
            self.old_pos = event.globalPos()

    def mouseMoveEvent(self, event):
        if event.buttons() == Qt.LeftButton:
            delta = event.globalPos() - self.old_pos
            self.move(self.x() + delta.x(), self.y() + delta.y())
            self.old_pos = event.globalPos()

    def init_tray(self):
        self.trayicon.setIcon(QIcon('ali_Screen_Recorder.ico'))
        self.trayicon.setVisible(True)

        self.trayicon_menu = QMenu()

        # 显示/隐藏窗口
        self.trayicon_menu.addAction('显示/隐藏', lambda: self.hide() if self.isVisible() else self.show())

        # 退出
        self.trayicon_menu.addAction('退出', self.close)

        # 录制动作，保存为成员变量，方便修改文本
        self.tray_record_action = self.trayicon_menu.addAction('开始录制', self.toggle_record)

        self.trayicon.setContextMenu(self.trayicon_menu)

    def toggle_record(self):
        """
        托盘菜单录制开关，自动更新文本和主窗口状态
        """
        if self.record_end_flag:
            # 开始录制
            self.run()
            # 更新托盘菜单文本
            self.tray_record_action.setText('停止录制')
        else:
            # 停止录制
            self.stop()
            # 更新托盘菜单文本
            self.tray_record_action.setText('开始录制')


if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = myUI()
    w.show()
    sys.exit(app.exec_())
